from config import chat_config
from dashscope import Assistants,Threads,Runs,Messages,Steps
import json
class Chat:
    def __init__(self):
        if chat_config["assistant_id"]=="":
            self.assistant_id = Assistants.create(api_key=chat_config["api_key"],
                                                  model=chat_config["data"]["model"],
                                                  name=chat_config["data"]["name"],
                                                  description=chat_config["data"]["description"],
                                                  instructions=chat_config["data"]["instructions"],
                                                  tools=chat_config["data"]["tools"],)['id']
            chat_config["assistant_id"]=self.assistant_id
            with open('config.py', 'w', encoding='utf-8') as f:
                f.write('chat_config =')
                json.dump(chat_config, f, ensure_ascii=False, indent=4)
        else:
            self.assistant_id = chat_config["assistant_id"]
        self.api_key = chat_config["api_key"]
    def create_chat(self,user_name):
        try:
            thread_id=Threads.create(api_key=self.api_key,messages=[{"role": "user", "content": "我叫"+user_name}]).id
            return thread_id
        except:
            return None
    def send_message(self,message,thread_id):
        Messages.create(api_key=self.api_key,thread_id=thread_id,content=message,role="user")
        run=Runs.create(api_key=self.api_key,thread_id=thread_id,assistant_id=self.assistant_id)
        run=Runs.wait(api_key=self.api_key,run_id=run['id'],thread_id=thread_id)
        msgs = Messages.list(thread_id,api_key=chat_config["api_key"])
        return msgs["data"][0]["content"][0]["text"]["value"]
